package com.cn.study.filter;

import com.alibaba.fastjson.JSONObject;
import com.cn.study.access.Signature;
import com.cn.study.access.SignatureFactory;
import com.cn.study.entity.ResultVO;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author mjy
 * 此出为全局过滤器，只做全局处理(如认证)
 * @date 2021/09/13
 * @description
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 全局过滤器判断逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        Signature sinature = SignatureFactory.createSinature(path);
        ResultVO resultVO = sinature.verifySignature(request);
        if (resultVO != null) {
            String rest = JSONObject.toJSONString(resultVO);
            DataBuffer buffer = response.bufferFactory().wrap(rest.getBytes());
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }


    /**
     * 设置过滤器的执行顺序,数值越小,优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
